﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing.Design;
using System.Windows.Forms.Design;
using System.Windows.Forms;

namespace TA.Win.Utils.Design
{
	/// <summary>
	/// Provides a user interface which can edit a collection of strings.
	/// </summary>
	/// <typeparam name="T"></typeparam>
	public class StringCollectionEditor<T> : BaseFormEditor<StringCollectionDialog>
		where T : IStringOptionsProvider, new()
	{
		/// <summary>
		/// Edits the specified object's value using the editor style indicated by the System.Drawing.Design.UITypeEditor.GetEditStyle() method.
		/// </summary>
		/// <param name="context"></param>
		/// <param name="provider"></param>
		/// <param name="value"></param>
		/// <returns></returns>
		public override object EditValue(System.ComponentModel.ITypeDescriptorContext context, IServiceProvider provider, object value)
		{
			if (provider != null && context != null)
			{
				IWindowsFormsEditorService editorservice = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));
				List<string> list = value as List<string>;
				if (editorservice != null && list != null)
				{
					T t = new T();
					StringOptions options = t.GetOptions(context, provider);
					this.Form.Options = options;

					this.Form.Value = list.ToArray();
					DialogResult dr = this.Form.ShowDialog();
					if (dr == DialogResult.OK)
					{
						list.Clear();
						list.AddRange(this.Form.Value);
						context.OnComponentChanged();
						return list;
					}
				}
			}

			return value;
		}

	}
}
